package com.example.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

import javax.annotation.Resource;

/**
 * @author ysb
 * @version V1.0
 * @Date 2024/11/12
 **/
@Configuration
public class MqttConfiguration {

    @Resource
    private MqttConfigurationProperties mqttConfigurationProperties;

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        // 创建客户端工程
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        // 创建MqttConnectionOptions对象, 设置连接参数
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(mqttConfigurationProperties.getUsername());
        options.setPassword(mqttConfigurationProperties.getPassword().toCharArray());
        options.setServerURIs(mqttConfigurationProperties.getUrl().split(","));
        factory.setConnectionOptions(options);
        return factory;
    }
}
